package com.sr.recitewords.exception;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sr.recitewords.common.enums.BizExceptionEnum;
import com.sr.recitewords.common.enums.ExpCodeEnum;
import org.slf4j.MDC;

/**
 * 自定义业务异常类
 */

public class BizException extends RuntimeException {

    private static final long serialVersionUID = 6361784176392089313L;

    // 错误码
    private String errorCode;
    // 错误信息
    private String errorMsg;

    // 日志追踪ID
    private String traceId = MDC.get("traceId");

    public BizException(BaseErrorInfo errorInfo) {
        super(errorInfo.getErrorMsg());
        this.errorCode = errorInfo.getErrorCode();
        this.errorMsg = errorInfo.getErrorMsg();
        fillCode();
    }

    public BizException(BizExceptionEnum bizExceptionEnum) {
        super(bizExceptionEnum.getDesc());
        this.errorCode = bizExceptionEnum.getCode();
        this.errorMsg = bizExceptionEnum.getDesc();
        fillCode();
    }

    public BizException(BaseErrorInfo errorInfo, String errorMsg) {
        super(errorMsg);
        this.errorCode = errorInfo.getErrorCode();
        this.errorMsg = errorMsg;
        fillCode();
    }

    public BizException(BaseErrorInfo errorInfo, Throwable cause) {
        super(errorInfo.getErrorMsg(), cause);
        this.errorCode = errorInfo.getErrorCode();
        this.errorMsg = errorInfo.getErrorMsg();
        fillCode();
    }

    public BizException(String errorCode, String errorMsg) {
        super(errorMsg);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        fillCode();
    }

    public BizException(String errorCode, String errorMsg, Throwable cause) {
        super(errorMsg, cause);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        fillCode();
    }

    private void fillCode() {
        if (StringUtils.isBlank(errorCode)) {
            errorCode = "1";
        }
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getTraceId() {
        return traceId;
    }

    public void setTraceId(String traceId) {
        this.traceId = traceId;
    }
}
